#coding=utf-8
# Copyright 2011 Kirill Gagarski <gagarin.gtn@gmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 3 or any later version.
from mercurial.dispatch import *
from mercurial.dispatch import _checkshellalias, _dispatch, _earlygetopt, \
  _getlocal, _loaded, _parse, _parseconfig

def parse_cmd(args, ui):
    """
    Разбирает команду так, как это делает mercurial. Основано на функции
    mercurial.dispatch._dispatch(). Использует приватные функции 
    (с префиксом "_" из пакета dispatch)
    """
    #args = req.args
    #ui = req.ui

    # read --config before doing anything else
    # (e.g. to change trust settings for reading .hg/hgrc)
    cfgs = _parseconfig(ui, _earlygetopt(['--config'], args))

    # check for cwd
    cwd = _earlygetopt(['--cwd'], args)
    if cwd:
        os.chdir(cwd[-1])

    rpath = _earlygetopt(["-R", "--repository", "--repo"], args)
    path, lui = _getlocal(ui, rpath)

    if util.version() < '2.0':
        shellaliasfn = _checkshellalias(ui, args)
    else:
        shellaliasfn = _checkshellalias(lui, ui, args)
    if shellaliasfn:
        return shellaliasfn()

    # Configure extensions in phases: uisetup, extsetup, cmdtable, and
    # reposetup. Programs like TortoiseHg will call _dispatch several
    # times so we keep track of configured extensions in _loaded.
    extensions.loadall(lui)
    exts = [ext for ext in extensions.extensions() if ext[0] not in _loaded]
    # Propagate any changes to lui.__class__ by extensions
    ui.__class__ = lui.__class__

    # (uisetup and extsetup are handled in extensions.loadall)

    for name, module in exts:
        cmdtable = getattr(module, 'cmdtable', {})
        overrides = [cmd for cmd in cmdtable if cmd in commands.table]
        if overrides:
            ui.warn(_("extension '{0}' overrides commands: {1}\n").\
                    format(name, " ".join(overrides)))
        commands.table.update(cmdtable)
        _loaded.add(name)

    # (reposetup is handled in hg.repository)

    addaliases(lui, commands.table)

    # check for fallback encoding
    fallback = lui.config('ui', 'fallbackencoding')
    if fallback:
        encoding.fallbackencoding = fallback

    fullargs = args
    return _parse(lui, args)